/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2024-01-09 10:15:21
 * @LastEditors: YangJianFei
 * @LastEditTime: 2024-10-09 10:02:27
 * @FilePath: \yt_devop_app\lib\pages\devices\device_controll\device_controll_controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:async';

import 'package:get/get.dart';
import 'package:xbr_gaode_amap/amap/src/core/map_event.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/model/device_obj/property_group_model.dart';
import 'package:yt_devops/pages/devices/device_controll/device_controll_utils.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/base_detail_controller/base_detail_controller.dart';
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';

import 'package:yt_devops/model/device_obj/group_config_model.dart';
import 'package:yt_devops/model/device_obj/product_config_model.dart';
import 'package:yt_devops/model/device_obj/service_config_model.dart';
import 'package:yt_devops/model/device_obj/tab_item_config_model.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

class DeviceControllController extends BaseDetailController
    with GetTickerProviderStateMixin {
  /// 订阅
  UseSubsribe subsribe = UseSubsribe(isContainDeviceId: true);

  /// 从设备订阅
  UseSubsribe subDevicesSubsribe = UseSubsribe(isContainDeviceId: true);

  ///
  StreamSubscription<Map<String, dynamic>>? subscription;

  ///
  StreamSubscription<Map<String, dynamic>>? subDevicesSubscription;

  Map<String, dynamic> dataSource = {};

  List<ProductConfigModel> groupConfigList = [];

  /// 1远程控制  0参数设置
  String title = '';

  /// 设备id
  late int deviceId;

  RxMap pageComponentMap = {}.obs;

  /// 从设备id列表
  List<int> subDeviceIds = [];
  @override
  void onInit() {
    if (Get.arguments != null) {
      title = Get.arguments['title'];
      deviceId = Get.arguments['deviceId'];
      var page = Get.arguments['page'];
      subDeviceIds =
          DeviceControllUtils.getDeviceIdFromTempl(page['children'] ?? []);
      initModel(page);
      initSubscribe();
    }
    super.onInit();
  }

  initSubscribe() {
    subscription = subsribe.start([deviceId], true).stream.listen((event) {
          dataSource.addAll(event);
          update();
        });

    if (subDeviceIds.isNotEmpty) {
      subDevicesSubscription =
          subDevicesSubsribe.start(subDeviceIds, true).stream.listen((event) {
        dataSource.addAll(event);
        update();
      });
    }
  }

  /// 初始化服务的模型
  initModel(Map page) {
    List children = page['children'] ?? [];

    for (var e in children) {
      ProductConfigModel? model = getGroupItem(e as Map<String, dynamic>);
      if (model != null) {
        groupConfigList.add(model);
      }
    }
  }

  ProductConfigModel? getGroupItem(Map<String, dynamic> item) {
    switch (item['type']) {
      case 'group':
        List childrenModel = [];
        item['children']?.forEach((element) {
          var groupModel = getGroupItem(element);
          if (groupModel != null) {
            childrenModel.add(groupModel);
          }
        });
        return GroupConfigModel.fromJson(item)..setChildren = childrenModel;

      case 'service':
        return ServiceConfigModel.fromJson(item);

      case 'propertyGroup':
        return PropertyGroupModel.fromJson(item);

      case 'tab':
        var tabItems = item['children'] ?? [];

        List<TabItemConfigModel> tabItemConfigList = [];
        for (var item in tabItems) {
          if (item['type'] == 'tabItem') {
            if (!FuncUtils.isListEmpty(item['children'])) {
              List tabGroupItems = [];
              item['children']?.forEach(
                (tabGroupItem) {
                  var groupModel = getGroupItem(tabGroupItem);
                  if (groupModel != null) {
                    tabGroupItems.add(groupModel);
                  }
                },
              );
              var tabItemConfigModel = TabItemConfigModel.fromJson(item)
                ..setChildren = tabGroupItems;
              tabItemConfigList.add(tabItemConfigModel);
            }
          }
        }
        return ProductConfigModel<TabItemConfigModel>.fromJson(item)
          ..setChildren = tabItemConfigList;

      case 'pageComponent':
        pageComponentMap.value = item;
        pageComponentMap.refresh();
        return null;

      case 'component':
        return ProductConfigModel.fromJson(item);

      default:
        return null;
    }
  }

  bool isShowGroupName(GroupConfigModel groupConfigModel) {
    var hasChildren = !FuncUtils.isListEmpty(groupConfigModel.children);
    var haName = !FuncUtils.isEmpty(groupConfigModel.name);

    if (hasChildren) {
      return groupConfigModel.children!.length > 1 && haName ||
          groupConfigModel.children!.first.showType ==
              DeviceModelShowType.hideName;
    } else {
      return false;
    }
  }

  TabController getTabController(int length) {
    return TabController(length: length, vsync: this);
  }

  /// 判断是否有编辑权限
  bool hasEditAuthority(List? authority) {
    return FuncUtils.isPassAuthority(authority?.map((e) => e.edit).toList(),
        permissionSource: UserEntityManager().webPermission);
  }

  @override
  void onReady() {}

  @override
  void onClose() {
    subscription?.cancel();
    subDevicesSubscription?.cancel();
    subsribe.closeListen();
    subDevicesSubsribe.closeListen();

    super.onClose();
  }
}
